package com.pai4j.ugc.service.chain;

import com.pai4j.common.enums.PromptTemplateEnum;
import com.pai4j.common.service.FreeMarkEngineService;
import com.pai4j.common.util.JsonUtil;
import com.pai4j.domain.dto.aigc.ChatCompletionMessageRequest;
import com.pai4j.domain.dto.llm.ChatCompletionMessage;
import com.pai4j.domain.dto.llm.ChatCompletionResponse;
import com.pai4j.domain.vo.llm.ChatMessageRole;
import com.pai4j.domain.vo.request.request.CommentSaveVO;
import com.pai4j.domain.vo.response.moment.AiContent;
import com.pai4j.domain.vo.response.moment.MomentVO;
import com.pai4j.remote.act.ICommentClient;
import com.pai4j.ugc.service.MoonshotAIService;
import com.pai4j.ugc.service.ai.AiContentPersistService;
import com.pai4j.ugc.service.ai.AiContentRetryService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 *  动态Ai评论 处理
 * @author  CYM_pai
 * @date  2025/8/16 11:07
 */
@Slf4j
@Component
public class MomentCommentHandler implements MomentPublishHandler {


    @Autowired
    private FreeMarkEngineService freeMarkEngineService;

    @Resource
    private ICommentClient commentClient;

    @Resource
    private MoonshotAIService moonshotAIService;

    @Value("${AI.aiAccount}")
    String  aiAccount;


    @Override
    public void handle(MomentVO moment, MomentPublishHandlerChain chain) throws Exception {

        // 这里我们仅支持对正文内容的审核
        String content = moment.getContent();
        if (StringUtils.isBlank(content)) {
            chain.handle(moment, chain);
            return;
        }
        String author = moment.getAuthor();
        if (StringUtils.isBlank(author)) {
            chain.handle(moment, chain);
            return;
        }

        String templateName = PromptTemplateEnum.MOMENT_COMMENT.getPath();
        Map<String, Object> vars = new HashMap<>();
        vars.put("author", author);
        vars.put("input", content);
        String prompt;
        try {
            prompt = freeMarkEngineService.getContentByTemplate(templateName, vars);
        } catch (Exception e) {
            log.error("[π圈动态AI评论异常] ===> prompt模版引擎模版渲染失败！vars:{}",
                    JsonUtil.toJsonString(vars), e);
            chain.handle(moment, chain);
            return;
        }
        // 将用户的提示信息封装成一个ChatCompletionMessage对象，并创建一个包含该消息的列表
        // 这里只包含一个消息，因为当前场景是一次用户请求对应一次模型回复
        ChatCompletionMessageRequest chatCompletionMessageRequest = new ChatCompletionMessageRequest(prompt,null, null);
        final List<ChatCompletionMessage> messageList = Arrays.asList(
                new ChatCompletionMessage(ChatMessageRole.USER.value(),
                        chatCompletionMessageRequest.getPrompt()));

        ChatCompletionResponse chatCompletionResponse = moonshotAIService.chat(messageList);
        String aiComment = null;
        if (chatCompletionResponse != null ) {
            aiComment = chatCompletionResponse.getChoices().get(0).getMessage().getContent();
            if (aiComment != null) {
                CommentSaveVO commentSaveVO = new CommentSaveVO();
                commentSaveVO.setResourceId(moment.getId());
                commentSaveVO.setResourceType("MOMENT");
                //这个author是评论作者，不是动态作者，是AI账号
                commentSaveVO.setAuthorId(aiAccount);
                commentSaveVO.setContent(aiComment);
                commentSaveVO.setIp(moment.getIp());
                commentClient.saveComment(commentSaveVO);
            } else {
                // AI评论失败
                log.warn("π圈动态AI评论异常: momentId={}, aiComment={}", moment.getId(), aiComment);

            }
            log.info("[π圈动态AI评论结果] ===> 内容:{}", aiComment);
        } else {
            log.error("[π圈动态AI评论异常] ===> LLM Chat Error！prompt:{}", prompt);
            chain.handle(moment, chain);
            return;
        }
        chain.handle(moment, chain);
    }
}